<template>
  <div class="user-create-container">
    <el-card class="form-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="title">新增用户</span>
          <el-button @click="$router.back()">
            <IconifyIconOffline icon="ep:back" class="mr-1" />
            返回
          </el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="user-form"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <h3 class="section-title">基本信息</h3>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用户名" prop="username">
                <el-input
                  v-model="form.username"
                  placeholder="请输入用户名"
                  clearable
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="真实姓名" prop="realName">
                <el-input
                  v-model="form.realName"
                  placeholder="请输入真实姓名"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="手机号" prop="phone">
                <el-input
                  v-model="form.phone"
                  placeholder="请输入手机号"
                  clearable
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input
                  v-model="form.email"
                  placeholder="请输入邮箱"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="密码" prop="password">
                <el-input
                  v-model="form.password"
                  type="password"
                  placeholder="请输入密码"
                  show-password
                  clearable
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input
                  v-model="form.confirmPassword"
                  type="password"
                  placeholder="请再次输入密码"
                  show-password
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 个人信息 -->
        <div class="form-section">
          <h3 class="section-title">个人信息</h3>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="性别">
                <el-radio-group v-model="form.gender">
                  <el-radio value="male">男</el-radio>
                  <el-radio value="female">女</el-radio>
                  <el-radio value="other">其他</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="生日">
                <el-date-picker
                  v-model="form.birthday"
                  type="date"
                  placeholder="选择生日"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="头像">
            <div class="avatar-upload">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-success="handleAvatarSuccess"
                action="#"
              >
                <img v-if="form.avatar" :src="form.avatar" class="avatar" />
                <div v-else class="avatar-placeholder">
                  <IconifyIconOffline icon="ep:plus" class="avatar-icon" />
                  <div class="avatar-text">上传头像</div>
                </div>
              </el-upload>
              <div class="upload-tips">
                <p>支持 JPG、PNG 格式，文件大小不超过 2MB</p>
                <p>建议尺寸：200x200 像素</p>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="地址">
            <el-input
              v-model="form.address"
              type="textarea"
              :rows="3"
              placeholder="请输入详细地址"
            />
          </el-form-item>
        </div>

        <!-- 角色权限 -->
        <div class="form-section">
          <h3 class="section-title">角色权限</h3>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="角色" prop="role">
                <el-select
                  v-model="form.role"
                  placeholder="选择角色"
                  style="width: 100%"
                >
                  <el-option label="管理员" value="admin">
                    <div class="role-option">
                      <span>管理员</span>
                      <span class="role-desc">拥有系统所有权限</span>
                    </div>
                  </el-option>
                  <el-option label="运营" value="operator">
                    <div class="role-option">
                      <span>运营</span>
                      <span class="role-desc">拥有内容管理权限</span>
                    </div>
                  </el-option>
                  <el-option label="普通用户" value="user">
                    <div class="role-option">
                      <span>普通用户</span>
                      <span class="role-desc">基础功能权限</span>
                    </div>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="状态">
                <el-radio-group v-model="form.status">
                  <el-radio value="active">正常</el-radio>
                  <el-radio value="disabled">禁用</el-radio>
                  <el-radio value="pending">待验证</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="权限说明">
            <div class="permission-info">
              <div v-if="form.role === 'admin'" class="permission-item">
                <IconifyIconOffline
                  icon="ep:check"
                  class="permission-icon success"
                />
                <span>系统管理：用户管理、角色管理、系统设置</span>
              </div>
              <div v-if="form.role === 'admin'" class="permission-item">
                <IconifyIconOffline
                  icon="ep:check"
                  class="permission-icon success"
                />
                <span>内容管理：活动管理、赛事管理、资讯管理</span>
              </div>
              <div
                v-if="form.role === 'admin' || form.role === 'operator'"
                class="permission-item"
              >
                <IconifyIconOffline
                  icon="ep:check"
                  class="permission-icon success"
                />
                <span>运营管理：订单管理、数据统计、广告管理</span>
              </div>
              <div class="permission-item">
                <IconifyIconOffline
                  icon="ep:check"
                  class="permission-icon success"
                />
                <span>基础功能：个人信息、参与活动、查看内容</span>
              </div>
            </div>
          </el-form-item>
        </div>

        <!-- 其他设置 -->
        <div class="form-section">
          <h3 class="section-title">其他设置</h3>

          <el-form-item label="账户设置">
            <el-checkbox-group v-model="form.settings">
              <el-checkbox value="emailNotification">邮件通知</el-checkbox>
              <el-checkbox value="smsNotification">短信通知</el-checkbox>
              <el-checkbox value="forcePasswordChange"
                >首次登录强制修改密码</el-checkbox
              >
              <el-checkbox value="accountExpiry">账户有效期限制</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item
            v-if="form.settings.includes('accountExpiry')"
            label="账户有效期"
          >
            <el-date-picker
              v-model="form.expiryDate"
              type="date"
              placeholder="选择过期日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 200px"
            />
          </el-form-item>

          <el-form-item label="备注">
            <el-input
              v-model="form.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </div>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <el-button @click="$router.back()">取消</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" :loading="submitting" @click="handleSubmit">
            创建用户
          </el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, type FormInstance, type UploadProps } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";

const router = useRouter();
const formRef = ref<FormInstance>();
const submitting = ref(false);

// 表单数据
const form = reactive({
  username: "",
  realName: "",
  phone: "",
  email: "",
  password: "",
  confirmPassword: "",
  gender: "male",
  birthday: "",
  avatar: "",
  address: "",
  role: "user",
  status: "active",
  settings: [],
  expiryDate: "",
  remark: ""
});

// 验证规则
const rules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      min: 3,
      max: 20,
      message: "用户名长度在 3 到 20 个字符",
      trigger: "blur"
    },
    {
      pattern: /^[a-zA-Z0-9_]+$/,
      message: "用户名只能包含字母、数字和下划线",
      trigger: "blur"
    }
  ],
  realName: [
    { required: true, message: "请输入真实姓名", trigger: "blur" },
    { min: 2, max: 10, message: "姓名长度在 2 到 10 个字符", trigger: "blur" }
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱格式", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur" },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,}$/,
      message: "密码必须包含大小写字母和数字",
      trigger: "blur"
    }
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value !== form.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
  role: [{ required: true, message: "请选择角色", trigger: "change" }]
};

// 头像上传前验证
const beforeAvatarUpload: UploadProps["beforeUpload"] = rawFile => {
  const isJPGOrPNG =
    rawFile.type === "image/jpeg" || rawFile.type === "image/png";
  const isLt2M = rawFile.size / 1024 / 1024 < 2;

  if (!isJPGOrPNG) {
    ElMessage.error("头像只能是 JPG 或 PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("头像大小不能超过 2MB!");
    return false;
  }
  return true;
};

// 头像上传成功
const handleAvatarSuccess: UploadProps["onSuccess"] = response => {
  // 这里应该处理上传成功后的响应
  form.avatar =
    "https://trae-api-sg.mchost.guru/api/ide/v1/text_to_image?prompt=professional%20user%20avatar&image_size=square";
  ElMessage.success("头像上传成功");
};

// 重置表单
const handleReset = () => {
  formRef.value?.resetFields();
  Object.assign(form, {
    username: "",
    realName: "",
    phone: "",
    email: "",
    password: "",
    confirmPassword: "",
    gender: "male",
    birthday: "",
    avatar: "",
    address: "",
    role: "user",
    status: "active",
    settings: [],
    expiryDate: "",
    remark: ""
  });
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    submitting.value = true;

    // 这里应该调用API创建用户
    await new Promise(resolve => setTimeout(resolve, 1000)); // 模拟API调用

    ElMessage.success("用户创建成功");
    router.push("/user/list");
  } catch (error) {
    console.error("表单验证失败:", error);
  } finally {
    submitting.value = false;
  }
};
</script>

<style scoped lang="scss">
.user-create-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.form-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
  }
}

.user-form {
  .form-section {
    margin-bottom: 30px;

    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      margin: 0 0 20px 0;
      padding-bottom: 8px;
      border-bottom: 2px solid #409eff;
    }
  }
}

.avatar-upload {
  display: flex;
  align-items: flex-start;
  gap: 20px;

  .avatar-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: all 0.3s;

      &:hover {
        border-color: #409eff;
      }
    }
  }

  .avatar {
    width: 100px;
    height: 100px;
    object-fit: cover;
    display: block;
  }

  .avatar-placeholder {
    width: 100px;
    height: 100px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fafafa;

    .avatar-icon {
      font-size: 24px;
      color: #8c939d;
      margin-bottom: 8px;
    }

    .avatar-text {
      font-size: 12px;
      color: #8c939d;
    }
  }

  .upload-tips {
    flex: 1;

    p {
      margin: 0 0 4px 0;
      font-size: 12px;
      color: #909399;
    }
  }
}

.role-option {
  display: flex;
  flex-direction: column;

  .role-desc {
    font-size: 12px;
    color: #909399;
    margin-top: 2px;
  }
}

.permission-info {
  .permission-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;

    .permission-icon {
      font-size: 14px;
      margin-right: 8px;

      &.success {
        color: #67c23a;
      }
    }

    span {
      font-size: 14px;
      color: #606266;
    }
  }
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding-top: 20px;
  border-top: 1px solid #f0f2f5;
}

@media (max-width: 768px) {
  .user-create-container {
    padding: 10px;
  }

  .form-card {
    max-width: 100%;
  }

  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .avatar-upload {
    flex-direction: column;

    .upload-tips {
      margin-top: 12px;
    }
  }

  .form-actions {
    flex-direction: column;

    .el-button {
      width: 100%;
    }
  }
}
</style>
